//
//  AppLocalManager.m
//  AppsTemplate
//
//  Created by Maple on 8/4/14.
//  Copyright (c) 2014 maple. All rights reserved.
//
#import "AppLocalManager.h"
#include "sys/stat.h"
#import <sys/xattr.h>
#import "CommonUtilityjudge.h"
static AppLocalManager *localManager;
#define NSUSERDOCUMENT(dir)  [NSString stringWithFormat:@"%@/CachesImage",dir]
#define NSCACHESDATADOCUMENT(dir)  [NSString stringWithFormat:@"%@/CachesData",dir]
#define NSTEMPDATADOCUMENT(dir)  [NSString stringWithFormat:@"%@/TempData",dir]
@interface AppLocalManager()
@property (nonatomic,assign)BOOL changeUser_B;
@end
@implementation AppLocalManager

#pragma mark -
#pragma mark Singleton Method

+ (id)sharedManager{
	@synchronized([AppLocalManager class]) {
		if (!localManager) {
			localManager = [[self alloc] init];
            localManager.changeUser_B = NO;
		}
		return localManager;
	}
	return nil;
}


- (void)saveData:(id)_data andKey:(NSString*)_key {
    [[NSUserDefaults standardUserDefaults] setValue:_data forKey:_key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)DeleteDataByKey:(NSString *)_key
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:_key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (id)getDataByKey:(NSString*)_key {
    return [[NSUserDefaults standardUserDefaults] valueForKey:_key];
}

- (void)removeImageFromLocal:(NSString *)name{
    
    @try {
        BOOL isPng = true;
        NSString *substring = [name copy];
        if(name && [name length] > 7){
            NSString *temp = [name substringWithRange:NSMakeRange(0, 7)];
            if([[temp lowercaseString] isEqualToString:[@"http://" lowercaseString]]){
                substring = [name substringFromIndex:7];
            }
            substring = [substring stringByReplacingOccurrencesOfString:@"/" withString:@"~###~"];
            NSRange range = [[substring lowercaseString] rangeOfString:@"png"];
            if(range.length == 0){
                isPng = false;
            }
        }
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *picPath = [NSUSERDOCUMENT([paths objectAtIndex:0]) stringByAppendingPathComponent:substring];
        if([[NSFileManager defaultManager] fileExistsAtPath:picPath isDirectory:NO]){
            [[NSFileManager defaultManager] removeItemAtPath:picPath error:nil];
        }

    }
    @catch (NSException *exception) {
        
    }
}

- (void)removeLocalImageList:(NSMutableArray *)imageList{
    
    for (NSString *picUrl in imageList) {
        if ([self imageExists:picUrl]) {
              [self removeImageFromLocal:picUrl];
        }
    }
    
}


- (BOOL)saveImageToLocal:(NSString *)name image:(UIImage *)image {
    //判断是否含有http://
    @try {
        BOOL isPng = true;
        NSString *substring = [name copy];
        if(name && [name length] > 7){
            NSString *temp = [name substringWithRange:NSMakeRange(0, 7)];
            if([[temp lowercaseString] isEqualToString:[@"http://" lowercaseString]]){
                substring = [name substringFromIndex:7];
            }
            substring = [substring stringByReplacingOccurrencesOfString:@"/" withString:@"~###~"];
            NSRange range = [[substring lowercaseString] rangeOfString:@"png"];
            if(range.length == 0){
                isPng = false;
            }
        }
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *picPath = [NSUSERDOCUMENT([paths objectAtIndex:0]) stringByAppendingPathComponent:substring];
        if([[NSFileManager defaultManager] fileExistsAtPath:picPath isDirectory:NO]){
            return NO;
        }

        
        BOOL writeSuccess = NO;
        if(isPng){
            NSData *data = UIImagePNGRepresentation(image);
            writeSuccess = [data writeToFile:picPath atomically:YES];
            
        }else{
            NSData *data = UIImageJPEGRepresentation(image,1.0);
            writeSuccess = [data writeToFile:picPath atomically:YES];
        }
        [self addSkipBackupAttributeToItemAtURL:[NSURL URLWithString:picPath]];
        
        return writeSuccess;
    }
    @catch (NSException *exception) {
        
    }
}


- (BOOL)saveImageToLocal:(NSString *)name imageData:(NSData *)imageData{
    //判断是否含有http://
    @try {
        BOOL isPng = true;
        NSString *substring = [name copy];
        if(name && [name length] > 7){
            NSString *temp = [name substringWithRange:NSMakeRange(0, 7)];
            if([[temp lowercaseString] isEqualToString:[@"http://" lowercaseString]]){
                substring = [name substringFromIndex:7];
            }
            substring = [substring stringByReplacingOccurrencesOfString:@"/" withString:@"~###~"];
            NSRange range = [[substring lowercaseString] rangeOfString:@"png"];
            if(range.length == 0){
                isPng = false;
            }
        }
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *picPath = [NSUSERDOCUMENT([paths objectAtIndex:0]) stringByAppendingPathComponent:substring];
        if([[NSFileManager defaultManager] fileExistsAtPath:picPath isDirectory:NO]){
            return NO;
        }
        
        
        BOOL writeSuccess = NO;
        if(isPng){
            writeSuccess = [imageData writeToFile:picPath atomically:YES];
            
        }else{
            writeSuccess = [imageData writeToFile:picPath atomically:YES];
        }
        [self addSkipBackupAttributeToItemAtURL:[NSURL URLWithString:picPath]];
        
        return writeSuccess;
    }
    @catch (NSException *exception) {
        
    }
}

- (UIImage *)getImageFromLocal:(NSString *)name {
    @try {
        NSString *substring = [name copy];
        if(name && [name length] > 7){
            NSString *temp = [name substringWithRange:NSMakeRange(0, 7)];
            if([[temp lowercaseString] isEqualToString:[@"http://" lowercaseString]]){
                substring = [name substringFromIndex:7];
            }
            substring = [substring stringByReplacingOccurrencesOfString:@"/" withString:@"~###~"];
        }
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,                                                                          NSUserDomainMask, YES);
        NSString *filePath = [NSUSERDOCUMENT([paths objectAtIndex:0]) stringByAppendingPathComponent:substring];
        UIImage *image = [UIImage imageWithContentsOfFile:filePath];
        
        
        return image;
    }
    @catch (NSException *exception) {
        
    }
}

- (BOOL)imageExists:(NSString *)name {
    @try {
        NSString *substring = [name copy];
        if(name && [name length] > 7){
            NSString *temp = [name substringWithRange:NSMakeRange(0, 7)];
            if([[temp lowercaseString] isEqualToString:[@"http://" lowercaseString]]){
                substring = [name substringFromIndex:7];
            }
            substring = [substring stringByReplacingOccurrencesOfString:@"/" withString:@"~###~"];
        }
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,                                                                          NSUserDomainMask, YES);
        NSString *filePath = [NSUSERDOCUMENT([paths objectAtIndex:0]) stringByAppendingPathComponent:substring];
        
        return [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:NO];
        
    }
    @catch (NSException *exception) {
        
    }
}

- (void)checkImageCaches{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *imagesDir = NSUSERDOCUMENT([paths objectAtIndex:0]);
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:imagesDir isDirectory:&isDir];
    
    if (!existed) {
        [fileManager createDirectoryAtPath:imagesDir withIntermediateDirectories:YES attributes:nil error:nil];
        
        [self addSkipBackupAttributeToItemAtURL:[NSURL URLWithString:imagesDir]];
        
    }else{
        
//        if ([self folderSizeAtPath:imagesDir] >= MAXIMAGESCACHESIZE) {
//            [fileManager removeItemAtPath:imagesDir error:nil];
//            [fileManager createDirectoryAtPath:imagesDir withIntermediateDirectories:YES attributes:nil error:nil];
//            
//            [self addSkipBackupAttributeToItemAtURL:[NSURL URLWithString:imagesDir]];
//        }
    }
    
    
}


- (NSString *)filterFilePath:(NSString *)filePath{
    
    if (!stringIsEmpty(filePath)) {
        NSArray *strList = [filePath componentsSeparatedByString:@"/"];
        return [strList lastObject];
    }
    return nil;
}


//返回文件目录的大小
- (long long) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeWithPath:fileAbsolutePath];
        
    }
    return folderSize;
}

//返回文件的大小
- (long long)fileSizeWithPath:(NSString *)filePath{
    //    oc实现
    //    NSFileManager *fileManager = [NSFileManager defaultManager];
    //
    //    return [[fileManager attributesOfItemAtPath:filePath error:nil]
    //            fileSize];
    
    //用C实现
    struct stat st;
    if(lstat([filePath cStringUsingEncoding:NSUTF8StringEncoding], &st) == 0){
        return st.st_size;
    }
    return 0;
}


//防止document目录下的文件提交到appStore
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
    const char* filePath = [[URL path] fileSystemRepresentation];
    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;
    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    return result == 0;
}

+ (NSString*)getPathByFileName:(NSString *)_fileName ofType:(NSString *)_type
{
    NSString* fileDirectory = [[[self getCacheDataDirectory] stringByAppendingPathComponent:_fileName] stringByAppendingPathExtension:_type];
    return fileDirectory;
}

+ (NSString*)getPathByFileName:(NSString *)_fileName{
    NSString* fileDirectory = [[self getCacheDataDirectory] stringByAppendingPathComponent:_fileName];
    return fileDirectory;
}


+ (NSString*)getCacheDataDirectory 
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    return NSCACHESDATADOCUMENT(path);
}


- (void)changeUser{
    self.changeUser_B = YES;
}

- (BOOL)getChangeUser{
    return self.changeUser_B;
}

- (void)dealloc{

}

@end
